<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="projectId">
        <el-input
            v-model="queryParams.projectId"
            placeholder="请输入项目编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customer">
        <el-input
            v-model="queryParams.customer"
            placeholder="请输入客户"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目组" prop="projectGroup">
        <el-input
            v-model="queryParams.projectGroup"
            placeholder="请输入项目组"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目状态" prop="projectStatus">
        <el-select v-model="queryParams.projectStatus" placeholder="请选择项目状态" clearable style="width: 180px;">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="projectLeaderName">
        <el-input
            v-model="queryParams.projectLeaderName"
            placeholder="请输入项目负责人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptName">
        <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
                        v-model="queryParams.startTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择项目开始时间"
                        style="width: 180px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择项目结束时间"
                        style="width: 180px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['erp:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['erp:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['erp:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['erp:project:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['erp:project:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="projectList" 
      @selection-change="handleSelectionChange"
      class="project-table"
      stripe
      border
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="项目编号" align="center" prop="projectId" width="120" show-overflow-tooltip />
      <el-table-column label="客户" align="center" prop="customer" width="120" show-overflow-tooltip>
        <template #default="scope">
          <el-tag type="info" effect="plain" size="small">{{ scope.row.customer || '暂无' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="left" prop="projectName" min-width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="project-name">
            <el-icon class="project-icon"><Document /></el-icon>
            <span class="project-title">{{ scope.row.projectName || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="项目组" align="center" prop="projectGroup" width="140" show-overflow-tooltip />
      <el-table-column label="项目状态" align="center" prop="projectStatus" width="100">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.projectStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="projectType" width="100" show-overflow-tooltip />
      <el-table-column label="项目负责人" align="center" prop="projectLeaderName" width="120">
        <template #default="scope">
          <div class="user-info" v-if="scope.row.projectLeaderName">
            <el-avatar :size="24" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="user-name">{{ scope.row.projectLeaderName }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName" width="120" show-overflow-tooltip>
        <template #default="scope">
          <span class="dept-name">{{ scope.row.deptName || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售人员" align="center" prop="saleName" width="120">
        <template #default="scope">
          <div class="user-info" v-if="scope.row.saleName">
            <el-avatar :size="24" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="user-name">{{ scope.row.saleName }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="项目开始时间" align="center" prop="projectStartTime" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.projectStartTime">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.projectStartTime, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="项目结束时间" align="center" prop="projectEndTime" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.projectEndTime">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.projectEndTime, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark" width="150" show-overflow-tooltip>
        <template #default="scope">
          <span class="remark-text">{{ scope.row.remark || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['erp:project:edit']"
            class="action-btn"
          >
            修改
          </el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['erp:project:remove']"
            class="action-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="客户" prop="customer">
          <el-input v-model="form.customer" placeholder="请输入客户" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目组" prop="projectGroup">
          <el-input v-model="form.projectGroup" placeholder="请输入项目组" />
        </el-form-item>
        <el-form-item label="项目状态" prop="projectStatus">
          <el-radio-group v-model="form.projectStatus">
            <el-radio
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="负责人" prop="projectLeader">
          <el-input 
            v-model="form.projectLeaderName" 
            placeholder="请选择项目负责人" 
            readonly
            @click="openUserSelect('leader')"
            style="cursor: pointer;"
          >
            <template #append>
              <el-button @click="openUserSelect('leader')" icon="User" style="white-space: nowrap;">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-input 
            v-model="form.deptName" 
            placeholder="选择负责人后自动填入" 
            readonly
            disabled
          >
            <template #prefix>
              <el-icon style="color: #909399;"><OfficeBuilding /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="projectStartTime">
          <el-date-picker clearable
                          v-model="form.projectStartTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择项目开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="projectEndTime">
          <el-date-picker clearable
                          v-model="form.projectEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择项目结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="销售人员" prop="saleId">
          <el-input 
            v-model="form.saleName" 
            placeholder="请选择销售人员" 
            readonly
            @click="openUserSelect('sale')"
            style="cursor: pointer;"
          >
            <template #append>
              <el-button @click="openUserSelect('sale')" icon="User">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 项目导入对话框 -->
    <el-dialog 
      :title="upload.title" 
      v-model="upload.open" 
      width="400px" 
      append-to-body
      :close-on-click-modal="!upload.isUploading"
      :close-on-press-escape="!upload.isUploading"
      :show-close="!upload.isUploading"
      @close="handleDialogClose"
    >
      <!-- 加载状态显示 -->
      <div v-if="upload.isUploading" class="upload-loading">
        <div class="loading-content">
          <el-icon class="loading-icon" size="40">
            <Loading />
          </el-icon>
          <div class="loading-text">正在导入数据，请稍候...</div>
          <el-progress 
            :percentage="upload.progress" 
            :show-text="false"
            style="margin-top: 10px;"
          />
        </div>
      </div>
      
      <!-- 上传组件 -->
      <el-upload
          v-else
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=true'"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="submitFileForm"
            :disabled="upload.isUploading"
            :loading="upload.isUploading"
          >
            {{ upload.isUploading ? '导入中...' : '确 定' }}
          </el-button>
          <el-button @click="cancelUpload" :disabled="upload.isUploading">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 人员选择对话框 -->
    <el-dialog 
      :title="userSelectType === 'leader' ? '选择项目负责人' : '选择销售人员'" 
      v-model="userSelectVisible" 
      width="400px" 
      append-to-body
    >
      <el-input 
        v-model="userSearchText" 
        placeholder="搜索成员/部门" 
        size="small" 
        clearable 
        style="margin-bottom: 10px;"
        prefix-icon="Search"
      />
      <el-tree
        ref="userTreeRef"
        :data="orgTreeData"
        :props="orgTreeProps"
        node-key="id"
        highlight-current
        @node-click="handleUserSelect"
        :default-expanded-keys="orgDefaultExpandedKeys"
        :filter-node-method="filterUserNode"
        style="max-height: 400px; overflow-y: auto;"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmUserSelect" :disabled="!selectedUser">确 定</el-button>
          <el-button @click="cancelUserSelect">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import { listProject, getProject, delProject, addProject, updateProject, importData } from "@/api/erp/project"
import { getUserDeptTree } from "@/api/organizational"
import { getToken } from "@/utils/auth"
import { Loading, Document, User, Calendar, OfficeBuilding } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { project_status } = proxy.useDict('project_status')

// 确保字典数据是响应式的
const statusOptions = computed(() => {
  return project_status.value || []
})

const projectList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 人员选择相关
const userSelectVisible = ref(false)
const userSelectType = ref('') // 'leader' 或 'sale'
const orgTreeData = ref([])
const orgTreeProps = { children: 'children', label: 'label' }
const selectedUser = ref(null)
const orgDefaultExpandedKeys = ref([])
const userSearchText = ref('')
const userTreeRef = ref(null)
const userIdToInfoMap = ref({})

// 导入参数
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 上传进度
  progress: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/erp/project/importData"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    customer: null,
    projectName: null,
    projectGroup: null,
    projectStatus: null,
    projectType: null,
    projectLeaderName: null,
    deptName: null,
    startTime: null,
    endTime: null,
    saleId: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

// 监听搜索文本变化
watch(userSearchText, (val) => {
  if (userTreeRef.value) {
    userTreeRef.value.filter(val)
    // 如果有搜索内容，展开所有节点
    if (val) {
      nextTick(() => {
        const allNodes = userTreeRef.value.store.nodesMap
        Object.keys(allNodes).forEach(key => {
          allNodes[key].expanded = true
        })
      })
    }
  }
})

/** 查询项目列表 */
function getList() {
  loading.value = true
  // 创建查询参数的副本，并确保projectStatus为数字类型
  const queryData = {
    ...queryParams.value,
    projectStatus: queryParams.value.projectStatus ? parseInt(queryParams.value.projectStatus) : null
  }
  
  listProject(queryData).then(response => {
    projectList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    customer: null,
    projectName: null,
    projectGroup: null,
    projectStatus: null,
    projectType: null,
    projectLeader: null,
    projectLeaderName: null,
    deptId: null,
    deptName: null,
    projectStartTime: null,
    projectEndTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    saleId: null,
    saleName: null
  }
  proxy.resetForm("projectRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加项目"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getProject(_id).then(response => {
    form.value = response.data
    
    // 处理项目负责人回显
    if (response.data.projectLeaderName) {
      form.value.projectLeaderName = response.data.projectLeaderName
    } else if (response.data.projectLeader) {
      // 如果没有姓名但有ID，尝试从映射中查找
      const leaderInfo = userIdToInfoMap.value[response.data.projectLeader]
      if (leaderInfo) {
        form.value.projectLeaderName = leaderInfo.userName
        // 同时填入部门信息
        form.value.deptId = leaderInfo.deptId
        form.value.deptName = leaderInfo.deptName
      } else {
        // 如果映射中没有，先加载组织架构数据
        if (orgTreeData.value.length === 0) {
          getUserDeptTree().then(res => {
            if (res.code === 200) {
              orgTreeData.value = adaptDeptTree(res.data)
              // 重新尝试查找
              const foundInfo = userIdToInfoMap.value[response.data.projectLeader]
              if (foundInfo) {
                form.value.projectLeaderName = foundInfo.userName
                form.value.deptId = foundInfo.deptId
                form.value.deptName = foundInfo.deptName
              }
            }
          })
        }
      }
    }
    
    // 处理销售人员回显
    if (response.data.saleName) {
      form.value.saleName = response.data.saleName
    } else if (response.data.saleId) {
      // 如果没有姓名但有ID，尝试从映射中查找
      const saleInfo = userIdToInfoMap.value[response.data.saleId]
      if (saleInfo) {
        form.value.saleName = saleInfo.userName
      } else {
        // 如果映射中没有，先加载组织架构数据
        if (orgTreeData.value.length === 0) {
          getUserDeptTree().then(res => {
            if (res.code === 200) {
              orgTreeData.value = adaptDeptTree(res.data)
              // 重新尝试查找
              const foundInfo = userIdToInfoMap.value[response.data.saleId]
              if (foundInfo) {
                form.value.saleName = foundInfo.userName
              }
            }
          })
        }
      }
    }
    
    open.value = true
    title.value = "修改项目"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate(valid => {
    if (valid) {
      // 创建提交数据的副本，并确保projectStatus为数字类型
      const submitData = {
        ...form.value,
        projectStatus: form.value.projectStatus ? parseInt(form.value.projectStatus) : null
      }
      
      if (form.value.id != null) {
        updateProject(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addProject(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除项目编号为"' + _ids + '"的数据项？').then(function() {
    return delProject(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erp/project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "项目导入"
  upload.open = true
}

/** 文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
  // 计算上传进度，但不直接显示100%，而是显示实际进度
  upload.progress = Math.round((event.loaded / event.total) * 90) // 最多显示90%，留10%给服务器处理
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  upload.progress = 100 // 完成时显示100%
  
  // 延迟一下让用户看到100%完成状态，然后显示结果
  setTimeout(() => {
    upload.isUploading = false
    proxy.$refs["uploadRef"].clearFiles()
    
    // 格式化导入结果消息
    const formattedMessage = formatImportResult(response.msg)
    
    // 显示导入结果，用户确认后再关闭窗口
    proxy.$alert(
      formattedMessage, 
      "导入结果", 
      { 
        dangerouslyUseHTMLString: true,
        callback: () => {
          // 用户确认查看结果后才关闭窗口并刷新列表
          upload.open = false
          upload.progress = 0
          getList()
        }
      }
    )
  }, 800) // 增加延迟时间，让用户更好地看到完成状态
}

/** 文件上传失败处理 */
function handleFileError(error, file, fileList) {
  upload.isUploading = false
  upload.progress = 0
  proxy.$modal.msgError("导入失败，请重试")
  proxy.$refs["uploadRef"].clearFiles()
}

/** 取消上传 */
function cancelUpload() {
  if (upload.isUploading) {
    // 如果正在上传，先确认是否要取消
    proxy.$modal.confirm('导入正在进行中，确定要取消吗？').then(() => {
      // 用户确认取消，停止上传
      proxy.$refs["uploadRef"].abort()
      upload.isUploading = false
      upload.progress = 0
      upload.open = false
      proxy.$refs["uploadRef"].clearFiles()
    }).catch(() => {
      // 用户取消了取消操作，什么都不做
    })
  } else {
    // 没有正在上传，直接关闭
    upload.open = false
    proxy.$refs["uploadRef"].clearFiles()
  }
}

/** 处理对话框关闭事件 */
function handleDialogClose() {
  if (upload.isUploading) {
    // 如果正在上传，阻止关闭并提示用户
    proxy.$modal.msgWarning('导入正在进行中，请等待完成或点击取消按钮')
    // 重新打开对话框
    nextTick(() => {
      upload.open = true
    })
  }
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

/** 格式化导入结果消息 */
function formatImportResult(message) {
  if (!message) return message
  
  // 解析消息中的统计信息和错误信息
  const stats = parseImportStats(message)
  
  let formattedHtml = `
    <div style="padding: 20px; font-family: 'Microsoft YaHei', sans-serif;">
      <div style="margin-bottom: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #303133; font-size: 16px; font-weight: 600;">
          📊 导入统计
        </h3>
        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 4px solid #409eff;">
  `
  
  if (stats.success > 0) {
    formattedHtml += `
          <div style="margin-bottom: 8px;">
            <span style="color: #67c23a; font-weight: 600;">✅ 成功导入：</span>
            <span style="color: #67c23a; font-weight: 600; font-size: 16px;">${stats.success} 条</span>
          </div>
    `
  }
  
  if (stats.failed > 0) {
    formattedHtml += `
          <div style="margin-bottom: 8px;">
            <span style="color: #f56c6c; font-weight: 600;">❌ 导入失败：</span>
            <span style="color: #f56c6c; font-weight: 600; font-size: 16px;">${stats.failed} 条</span>
          </div>
    `
  }
  
  formattedHtml += `
          <div>
            <span style="color: #909399; font-weight: 600;">📋 总计：</span>
            <span style="color: #303133; font-weight: 600; font-size: 16px;">${stats.total} 条</span>
          </div>
        </div>
      </div>
  `
  
  // 如果有错误信息，显示错误详情
  if (stats.errors && stats.errors.length > 0) {
    formattedHtml += `
      <div>
        <h3 style="margin: 0 0 15px 0; color: #f56c6c; font-size: 16px; font-weight: 600;">
          ⚠️ 错误详情
        </h3>
        <div style="background: #fef0f0; padding: 15px; border-radius: 8px; border-left: 4px solid #f56c6c; max-height: 300px; overflow-y: auto;">
          <ul style="margin: 0; padding-left: 20px; line-height: 1.6;">
    `
    
    stats.errors.forEach((error, index) => {
      formattedHtml += `
            <li style="margin-bottom: 8px; color: #606266;">
              <span style="color: #f56c6c; font-weight: 600;">第 ${error.row} 行：</span>
              <span>${error.message}</span>
            </li>
      `
    })
    
    formattedHtml += `
          </ul>
        </div>
      </div>
    `
  }
  
  formattedHtml += `</div>`
  
  return formattedHtml
}

/** 解析导入统计信息 */
function parseImportStats(message) {
  const stats = {
    success: 0,
    failed: 0,
    total: 0,
    errors: []
  }
  
  // 解析成功数量
  const successMatch = message.match(/(\d+)\s*条数据成功/)
  if (successMatch) {
    stats.success = parseInt(successMatch[1])
  }
  
  // 解析失败数量
  const failedMatch = message.match(/(\d+)\s*条数据格式不正确/)
  if (failedMatch) {
    stats.failed = parseInt(failedMatch[1])
  }
  
  stats.total = stats.success + stats.failed
  
  // 解析具体错误信息
  const errorPattern = /第\s*(\d+)\s*行[^：]*：([^<\n]+)/g
  let errorMatch
  while ((errorMatch = errorPattern.exec(message)) !== null) {
    stats.errors.push({
      row: errorMatch[1],
      message: errorMatch[2].trim()
    })
  }
  
  return stats
}

/** 人员树搜索过滤方法 */
function filterUserNode(value, data) {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 打开人员选择对话框 */
function openUserSelect(type) {
  userSelectType.value = type
  selectedUser.value = null
  userSearchText.value = ''
  userSelectVisible.value = true
  
  // 如果还没有加载组织架构数据，则加载
  if (orgTreeData.value.length === 0) {
    getUserDeptTree().then(res => {
      if (res.code === 200) {
        orgTreeData.value = adaptDeptTree(res.data)
        if (orgTreeData.value.length > 0) {
          orgDefaultExpandedKeys.value = [orgTreeData.value[0].id]
        }
      }
    })
  }
}

/** 处理人员选择 */
function handleUserSelect(node) {
  if (node.isUser) {
    selectedUser.value = node
  } else {
    selectedUser.value = null
  }
}

/** 确认选择人员 */
function confirmUserSelect() {
  if (selectedUser.value) {
    if (userSelectType.value === 'leader') {
      form.value.projectLeader = selectedUser.value.id
      form.value.projectLeaderName = selectedUser.value.label
      // 自动填入部门信息
      if (selectedUser.value.deptId && selectedUser.value.deptName) {
        form.value.deptId = selectedUser.value.deptId
        form.value.deptName = selectedUser.value.deptName
      }
    } else if (userSelectType.value === 'sale') {
      form.value.saleId = selectedUser.value.id
      form.value.saleName = selectedUser.value.label
    }
    userSelectVisible.value = false
    selectedUser.value = null
  }
}

/** 取消选择人员 */
function cancelUserSelect() {
  userSelectVisible.value = false
  selectedUser.value = null
  userSearchText.value = ''
}

/** 适配部门树数据结构 */
function adaptDeptTree(data) {
  const buildUserMap = (depts, parentDeptInfo = null) => {
    depts.forEach(dept => {
      const currentDeptInfo = {
        deptId: dept.deptId,
        deptName: dept.deptName
      }
      
      // 构建用户ID到信息的映射
      if (dept.userList) {
        dept.userList.filter(user => user.nickName !== 'admin' && user.nickName !== 'ry').forEach(user => {
          userIdToInfoMap.value[user.ddUserId] = {
            userName: user.nickName,
            deptId: dept.deptId,
            deptName: dept.deptName
          }
        })
      }
      // 递归处理子部门
      if (dept.children) {
        buildUserMap(dept.children, currentDeptInfo)
      }
    })
  }
  
  // 构建映射
  buildUserMap(data)
  
  return data.map(dept => ({
    id: dept.deptId,
    label: dept.deptName,
    children: [
      // 部门下的员工，过滤admin和ry
      ...(dept.userList ? dept.userList.filter(user => user.nickName !== 'admin' && user.nickName !== 'ry').map(user => ({
        id: user.ddUserId,
        label: user.nickName,
        isUser: true,
        deptId: dept.deptId,
        deptName: dept.deptName
      })) : []),
      // 子部门
      ...(dept.children ? adaptDeptTree(dept.children) : [])
    ]
  }))
}

// 初始化加载
getList()

// 预加载组织架构数据
getUserDeptTree().then(res => {
  if (res.code === 200) {
    orgTreeData.value = adaptDeptTree(res.data)
    if (orgTreeData.value.length > 0) {
      orgDefaultExpandedKeys.value = [orgTreeData.value[0].id]
    }
  }
})
</script>

<style scoped>
/* 表格样式优化 */
.project-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.project-table :deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

.project-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.project-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.project-table :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 项目名称样式 */
.project-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.project-icon {
  color: #409eff;
  font-size: 16px;
}

.project-title {
  font-weight: 500;
  color: #303133;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.user-avatar {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

.user-name {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
}

/* 日期信息样式 */
.date-info {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.date-icon {
  color: #67c23a;
  font-size: 14px;
}

/* 部门名称样式 */
.dept-name {
  color: #606266;
  font-size: 13px;
  padding: 2px 8px;
  background-color: #f0f2f5;
  border-radius: 12px;
  display: inline-block;
}

/* 备注文本样式 */
.remark-text {
  color: #909399;
  font-size: 13px;
  font-style: italic;
}

/* 暂无文本样式 */
.text-muted {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮样式 */
.action-btn {
  margin: 0 2px;
  font-size: 12px;
  padding: 4px 8px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 上传组件样式 */
.upload-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  text-align: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.loading-icon {
  animation: rotate 2s linear infinite;
  color: #409eff;
  margin-bottom: 16px;
}

.loading-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-table :deep(.el-table__header-wrapper),
  .project-table :deep(.el-table__body-wrapper) {
    font-size: 12px;
  }
  
  .user-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .project-name {
    flex-direction: column;
    gap: 4px;
  }
}

/* 人员选择对话框样式 */
.el-tree {
  font-size: 14px;
}

.el-tree .el-tree-node__content {
  height: 32px;
  line-height: 32px;
}

.el-tree .el-tree-node__content:hover {
  background-color: #f5f7fa;
}

.el-tree .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 用户节点特殊样式 */
.el-tree .el-tree-node[data-is-user="true"] > .el-tree-node__content {
  color: #409eff;
  font-weight: 500;
}

.el-tree .el-tree-node[data-is-user="true"] > .el-tree-node__content::before {
  content: "👤 ";
  margin-right: 4px;
}
</style>
